package com.draemoncode.weixindb.websocket;


import com.draemoncode.weixindb.server.CSession;
import com.draemoncode.weixindb.util.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.Session;

public class UISession {

    private final static Logger log = LoggerFactory.getLogger(CSession.class);

    private static Session session;

    public static void setSession(Session session){
        UISession.session = session;
    }

    public static Boolean isSessionExists(){
        return session != null;
    }

    public static void send(UIMessage uiMessage){
        if(session != null){
            if(session.isOpen()){
                try {
                    session.getBasicRemote().sendText(JSONUtil.toJson(uiMessage));
                } catch (Exception e) {
                    log.error("无法发送消息给UI:" + uiMessage, e);
//                    throw new BusiException(BusiExceptionConstant.UI_UN_CCONNECT, "无法发送消息给UI");
                }
            }else{
                log.info("与UI客户端失去连接");
//                throw new BusiException(BusiExceptionConstant.UI_UN_CCONNECT, "与UI客户端失去连接");
            }
        }else{
            log.info("UI客户端未连接");
//            throw new BusiException(BusiExceptionConstant.UI_UN_CCONNECT, "UI客户端未连接");
        }
    }

}
